package com.river;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;

/**
 * Created by jl on 2018/3/7.
 */
public class RiverWebSocketServer extends WebSocketServer {
    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String msg = address + "<加入>";
        System.out.println(msg);
        broadcastMessage(msg);
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String msg = address + "<离开>";
        System.out.println(msg);
        broadcastMessage(msg);
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        String address = webSocket.getRemoteSocketAddress().getAddress().getHostAddress();
        String msg = String.format("(%s)%s", address, s);
        System.out.println(msg);
        broadcastMessage(msg);
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        if (null != webSocket) {
            if (!webSocket.isClosed()) {
                webSocket.close(0);
            }
        }
        e.printStackTrace();
    }

    @Override
    public void onStart() {
        System.out.println("service started");
    }

    private void broadcastMessage(String msg) {
        Collection<WebSocket> connections = connections();
        for (WebSocket client : connections) {
            client.send(msg);
        }
    }

    public static void main(String[] args) {
        RiverWebSocketServer server = new RiverWebSocketServer();
        server.start();
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(in);
        while (true) {
            try {
                String msg = bufferedReader.readLine();
                server.broadcastMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
